<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use think\Session;
use think\Db;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Adminwork extends Backend
{
    
    /**
     * Adminwork模型对象
     * @var \app\admin\model\Adminwork
     */
    protected $model = null;
    protected  $admin_data = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'admin_id';
        $this->model = new \app\admin\model\Adminwork;
        $adminData = Session::get("admin");
        $linkAdmin = Db::name('Admin');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name')->alias('a')->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        $this->view->assign("statuslistList", $this->model->getStatuslistList());
        $this->view->assign('admin_data',$this->admin_data);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index($ids='')
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','admin_id','shen_text','title','brief','workfile','speedimages','speedfile','expire_date','wan_date','shen_date','shen_name','statuslist','admin_name','createtime','qilist']);
                $row->visible(['admin']);
				$row->getRelation('admin')->visible(['nickname']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign('ids',$ids);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill&&empty($params['admin_id'])) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['admin_name'] = $this->admin_data['nickname'];

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $authGroup = model('AuthGroup');
        $linkAdmin = model('admin');
        $childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection($authGroup::where('id', 'in', $childrenGroupIds)->select())->toArray();
        foreach ($groupList as $k=>$v){
            //查询admin
            $adminData = $linkAdmin->field('a.*')->alias('a')->join('fa_auth_group_access c','a.id = c.uid','LEFT')
                            ->where(array('c.group_id'=>$v['id']))->select();
            $adminData = collection($adminData)->toArray();
            $groupList[$k]['adminData'] = $adminData;
        }
        $this->view->assign('groupList',$groupList);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $params['admin_name'] = $this->admin_data['nickname'];
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $authGroup = model('AuthGroup');
        $linkAdmin = model('admin');
        $childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection($authGroup::where('id', 'in', $childrenGroupIds)->select())->toArray();
        foreach ($groupList as $k=>$v){
            $adminData = $linkAdmin->field('a.*')->alias('a')->join('fa_auth_group_access c','a.id = c.uid','LEFT')
                        ->where(array('c.group_id'=>$v['id']))->select();
            $groupList[$k]['adminData'] = $adminData;
        }
        $this->view->assign('groupList',$groupList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 批量更新(更多操作)
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                if (!$this->auth->isSuperAdmin()) {
                    $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                }
                if ($values) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    //过滤已经审核通过的数据
                    $idArray = $this->model->where(array('id'=>array('IN',$ids),'statuslist'=>array('IN','2')))->column('id');
                    if(!$idArray){
                        $this->error(__('没有待验收的数据'));
                    }
                    $ids = $idArray;
                    $count = 0;
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                    $values['shen_name'] = $this->admin_data['nickname'];
                    $values['shen_date'] = date('Y-m-d H:i:s',time());
                    foreach ($list as $index => $item) {
                        $count += $item->allowField(true)->isUpdate(true)->save($values);
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 工作台分类查询任务
     * $type:时间查询,默认查询今天的任务
     */
    public function work_type(){
        $type = $this->request->param('type',4);
        $where = array('admin_id'=>$this->admin_data['id']);
        $time = '';
        if($type==1){
            //查询当天任务
            $time = date('Y-m-d',time());
            $where['expire_date'] = array('EQ',$time);
        }else if($type==2){
            //查询明天工作
            $time = date('Y-m-d',strtotime('+1 day'));
            $where['expire_date'] = array('EQ',$time);
        }else if($type==3){
            //查询后天工作
            $time = date('Y-m-d',strtotime('+2 day'));
            $where['expire_date'] = array('EQ',$time);
        }else if($type==4){
            //未来七天工作
            $qiTime = date('Y-m-d',time());
            $time = date('Y-m-d',strtotime('+6 day'));
            $where['expire_date'] = array(array('EGT',$qiTime),array('ELT',$time));
        }
        $data = $this->model->field('*')->where($where)->order('id DESC')->select();
        $data = collection($data)->toArray();
        return json($data);
    }

    /**
     * 销售提交任务
     */
    public function sale_add($ids = ''){
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $workData = $this->model->where(array('id'=>$ids,'admin_id'=>$this->admin_data['id']))->find();
        if(!$workData){
            $this->error(__('您不存在此任务'));
        }else if($workData['statuslist']==4){
            //已经确认的任务
            $this->error(__('当前任务已经完成'));
        }
        if($this->request->post()){
            //post提交
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $params['statuslist'] = '2';
                    $params['wan_date'] = date('Y-m-d H:i:s',time());
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $this->view->assign('row',$workData);
            return $this->view->fetch();
        }
    }

    /**
     * 审核
     * @param string $ids
     * @param string $type
     */
    public function examine($ids='',$type=''){
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if(empty($type)){
            $this->error(__('缺少重要参数'));
        }else if($type!=3&&$type!=4){
            $this->error(__('不存在当前审核类型'));
        }
        $workData = $this->model->where(array('id'=>$ids))->find();
        if(!$workData){
            $this->error(__('不存在的审核数据'));
        }else if($workData['statuslist']==1){
            $this->error(__('还没有验收数据,不能审核'));
        }else if($workData['statuslist']==4){
            $this->error(__('当前任务已经完成'));
        }
        if($this->request->post()){
            //审核提交
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $params['statuslist'] = ''.$type.'';
                    $params['shen_date'] = date('Y-m-d H:i:s',time());
                    $params['shen_name'] = $this->admin_data['nickname'];
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            return $this->view->fetch();
        }
    }
}
